//
//  GTKeyBoardObserver.m
//  YueYTProject
//
//  Created by mingke on 2021/2/22.
//

#import "GTKeyBoardObserver.h"
#import <objc/runtime.h>
#import <UIKit/UIKit.h>

NSString *kKeyboardObserver = @"kKeyboardObserver";

@implementation GTKeyBoardObserver

//ios提供了一种可以在程序运行阶段动态给对象增加属性的方式
//也就是下面的代码段使用的方式--关联
//也就是使用objc_getAssociatedObject和objc_setAssociatedObject完成属性的获取和设置
+ (instancetype)observeOn:(NSObject *)obj callback:(void(^)(KeyboardInfo* kbinfo))callback {
    //先尝试获取到关联对象的属性
    GTKeyBoardObserver *tmp = objc_getAssociatedObject(obj, &kKeyboardObserver);
    
    if (tmp) {
        //如果真的存在此属性，就设置回调，准备返回
        tmp.callback = callback;
    } else {
        //如果不存在，就设置回调，并使用方法设置相应的属性
        tmp = [GTKeyBoardObserver new];
        tmp.callback = callback;
        
        objc_setAssociatedObject(obj, &kKeyboardObserver, tmp, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }
    return tmp;
}

//这个观察者，观察的是键盘的收起和放开状态，在此行为发生时，设置动画的参数
- (instancetype)init {
    if (self = [super init]) {
         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onKeyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
    }
    return self;
}

- (void)onKeyboardWillChangeFrame:(NSNotification *)noti {
    CGRect frame = [noti.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    NSTimeInterval duration = [noti.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    NSInteger curve = [noti.userInfo[UIKeyboardAnimationCurveUserInfoKey] integerValue];
    
    BOOL isShow = frame.origin.y < UIScreen.mainScreen.bounds.size.height;
    KeyboardInfo *kbinfo = [KeyboardInfo new];
    kbinfo.duration = duration;
    kbinfo.curve = curve;
    kbinfo.show = isShow;
    kbinfo.height = frame.size.height;
    
    if (self.callback) {
        self.callback(kbinfo);
    }
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillChangeFrameNotification object:nil];
}

@end

@implementation KeyboardInfo

@end
